import java.util.concurrent.CountDownLatch;

class ThreadTest {
    static public void main(String args[]) {
        ThreadTest t = new ThreadTest();
        TestRunnerable task = new TestRunnerable();
        try {
            t.timeTasks(100, task);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static class TestRunnerable implements Runnable {

        @Override
        public void run() {
            System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("子线程"+Thread.currentThread().getName()+"执行完成");
        }
    }

    public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i = 0; i < nThreads; i++) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException ignored) {
                    }
                }
            };
            t.start();
        }
        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        System.out.println(end - start);
        return end - start;
    }
}